// SStuff.MetaShaders.Compiler.Native.h

#pragma once
#include "D3D9.h"
#include "D3DX9.h"
#include <string>
#include "assert.h"

using namespace System;
using namespace System::Runtime::InteropServices;

namespace SStuff {
	namespace MetaEffects
	{
		namespace Compiler
		{
			namespace Native
			{
				public ref class NativeCompiler
				{
				public:
					static array<Byte>^ CompileShader(String^ source, String^ mainFunction, String^ profile)
					{
						char* nativeSoure = (char*) Marshal::StringToHGlobalAnsi(source).ToPointer();
						char* nativeFunction = (char*) Marshal::StringToHGlobalAnsi(mainFunction).ToPointer();
						char* nativeProfile = (char*) Marshal::StringToHGlobalAnsi(profile).ToPointer();
						
						array<Byte>^ result = nullptr;
						ID3DXBuffer* buffer;
						HRESULT hr = D3DXCompileShader (nativeSoure, source->Length, NULL, NULL, nativeFunction, nativeProfile, 0, &buffer, NULL, NULL);
						if(S_OK == hr)
						{
							result = gcnew array<Byte>(buffer->GetBufferSize());
							Marshal::Copy(IntPtr(buffer->GetBufferPointer()), result, 0, buffer->GetBufferSize());

							buffer->Release();
							buffer = NULL;
						}
						
						Marshal::FreeHGlobal(IntPtr(nativeSoure));
						Marshal::FreeHGlobal(IntPtr(nativeFunction));
						Marshal::FreeHGlobal(IntPtr(nativeProfile));
						return result;
					};
				};
			}
		}
	}
}
